package admin.controllers;

import helpers.DateHelper;
import helpers.EmailHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import data.EmailData;
import datastore.EmailDataFile;
import datastore.EmailDataStore;
import debugs.DealDebug;
import debugs.EmailDataStoreDebug;

import models.DealEmailModel;
import models.DealModel;
import models.EmailModel;
import models.EmailStatisticModel;
import models.GeoModel;

import admin.data.DealData;
import admin.data.DealEmailData;
import admin.data.EmailStatisticData;
import admin.data.GeoData;

public class SendDealEmailServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(SendDealEmailServlet.class
			.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		
		String path = ((HttpServletRequest) request).getRequestURI();

		String id = "";
		try {
			id = URLDecoder.decode(
					path.toLowerCase().replaceAll("/admin/dealsemail/sendemail/",
							""), "UTF-8").toUpperCase();
		} catch (Exception e) {
			response.sendRedirect("/admin/dealsemail/list");
			return;
		}
		DealEmailData dealEmailData = new DealEmailData();
		DealEmailModel dealEmail = dealEmailData.get(id);

		if (dealEmail == null) {
			session.setAttribute("error", "Không tìm thấy deal email có mã " + id);
			response.sendRedirect("/admin/dealsemail/list");
			return;
		}

		//Get all email
		EmailData emailData = new EmailData();
		ArrayList<EmailModel> emails = emailData.getAll();
		
		/*List<String> emails = new ArrayList<String>();
		
		EmailDataStore emailDataStore = EmailDataFile.getEmailByFileName(dealEmail.getCity());
		System.out.println(dealEmail.getCity());
		if (emailDataStore != null) {
			emails = emailDataStore.getEmails();
			EmailDataStoreDebug.debug(emailDataStore);
		}
		*/
		
		//Send email
		//................................
		int limit = 10000;
		int count = 1;
		List<String> lst_email = new ArrayList<String>();
		String str_email = "";
		for (int i = 0; i < emails.size(); i++) {
			count ++;
			if (count == limit) {
				lst_email.add(str_email);
				str_email = "";
			}
			
			if (!str_email.isEmpty()) str_email += ",";
			str_email += emails.get(i).getEmail();
		}
		if (!str_email.isEmpty()) {
			lst_email.add(str_email);
		}

		//Send mail
		for (int i = 0; i < lst_email.size(); i++) {
			String url = UrlHelper.getServerUrl(request) + "/print/dealsemail/preview/" + id;
			//System.out.println(dealEmail.getTitle() + "  ----- " + url + " ----------------- " + lst_email.get(i));
			SendDealEmailServlet.sendData("onsale365 <khuyenmai@onsale365.com.vn>", dealEmail.getTitle(), url, lst_email.get(i));
			session.setAttribute("infor", "Mail đã được gửi thành công!");
		}
		
		
		//Update data email send
		//MM/dd/yyyy - 08/30/2012
		String doc = DateHelper.dateToString(new Date(), "MM/dd/yyyy");
		EmailStatisticData emailStatisticData = new EmailStatisticData();
		EmailStatisticModel emailStatistic = emailStatisticData.getStatisticByDateString(doc);
		if (emailStatistic == null ) {
			emailStatistic = new EmailStatisticModel();
			emailStatistic.setDoc(doc);
			emailStatistic.setEmailCount(emails.size());
			emailStatistic.setDeliveryEmailCount(emails.size());
			emailStatisticData.insert(emailStatistic);
		}
		
		//Update status send
		dealEmail.setSended(true);
		dealEmailData.insert(dealEmail);
		
		
		response.sendRedirect("/admin/dealsemail/list");
		return;
	}
	
	public static void sendData(String fromEmail, String strSubject, String strUrl, String emails) {
		log.setLevel(Level.FINE);
		
		EmailHelper.sendMailFromUrl(fromEmail, strSubject, strUrl, emails);
		/*try {
			//URL url = new URL("http://localhost:8888/create-example");
			URL url = new URL("http://email-tests.appspot.com/mail-two");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	        connection.setDoOutput(true);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	        connection.setRequestProperty("Content-Language", "en-US");
	        
	        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	        writer.write("email=" + URLEncoder.encode(emails, "UTF-8"));
	        writer.write("&url=" + strUrl);
	        writer.write("&fromEmail=" + fromEmail);
	        writer.write("&strSubject=" + URLEncoder.encode(strSubject, "UTF-8"));
	        writer.close();
	        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        	log.info("send sucess emails ");
	        }
		} catch (Exception e) {
			// TODO: handle exception
		}*/
		
		
	}
}